package cn.wolfcode.mq;

/**
 * @ClassName OrderPeddingMQListener
 * @Author VCR
 * @Date 2022/1/2 18:10
 * @Version 1.0
 */

import cn.wolfcode.service.IOrderInfoService;
import cn.wolfcode.web.msg.SeckillCodeMsg;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

/**
 * 消费者RocketMQ
 */
@Component  // 交给Spring容器管理
@Slf4j
@RocketMQMessageListener(topic = MQConstant.ORDER_PEDDING_TOPIC,consumerGroup = "OrderPeddingMQConsumer")
public class OrderPeddingMQConsumer implements RocketMQListener<OrderMessage> { // 传入的是返回的消息类型

    @Autowired
    private IOrderInfoService orderInfoService;     // 注入该Service执行doSeckill方法

    @Autowired
    private RocketMQTemplate rocketMQTemplate;      // 注入RocketMQ发送消息
    @Override
    public void onMessage(OrderMessage orderMessage) {

        System.out.println("进入消费者创建订单逻辑");
        log.info("进入消费者创建订单逻辑");
        Integer time = orderMessage.getTime();
        Long seckillId = orderMessage.getSeckillId();
        String token = orderMessage.getToken();
        Long phone = orderMessage.getUserPhone();

        // 再次进行封装 将信息封装到OrderMQResult中
        OrderMQResult orderMQResult = new OrderMQResult();
        orderMQResult.setTime(time);
        orderMQResult.setSeckillId(seckillId);
        orderMQResult.setToken(token);
        String tag = "";
        try {
//            int test = 993 / 0;                             // 定义一个by zero异常测试程序执行失败
            // 执行doSeckill方法, 返回一个订单编号
            String orderNo = orderInfoService.doSeckill(time, seckillId, phone);
            orderMQResult.setOrderNo(orderNo);              // 成功传入订单编号
            tag = MQConstant.ORDER_RESULT_SUCCESS_TAG;

            // 订单超时 实现
            MessageBuilder<OrderMQResult> resultMessageBuilder = MessageBuilder.withPayload(orderMQResult);
            rocketMQTemplate.syncSend(MQConstant.ORDER_PAY_TIMEOUT_TOPIC,resultMessageBuilder.build(),5000,MQConstant.ORDER_PAY_TIMEOUT_DELAY_LEVEL);
        } catch (Exception e) {
            // 执行失败进入
            e.printStackTrace();    // 输出执行失败异常
            orderMQResult.setCode(SeckillCodeMsg.SECKILL_ERROR.getCode());  // 设置秒杀失败返回Code
            orderMQResult.setMsg(SeckillCodeMsg.SECKILL_ERROR.getMsg());    // 设置秒杀失败返回Msg
            tag = MQConstant.ORDER_RESULT_FAIL_TAG;
        }
        // 将封装好的OrderMQResult发送一次性消息到订单结果TOPIC中
//        rocketMQTemplate.sendOneWay(MQConstant.ORDER_RESULT_TOPIC,orderMessage);
        rocketMQTemplate.sendOneWay(MQConstant.ORDER_RESULT_TOPIC+":"+tag,orderMQResult);
    }
}
